#include "main_interface.h"
#include "ui_main_interface.h"

#include "global_variant.h"

QHash<int, QPair<QString, int>> g_Client2Hash;
QHash<QPair<QString, int>, int> g_Hash2Client;

#include <QMessageBox>
#include <QSqlQuery>
#include <QSqlError>
#include <QBitmap>
#include <QPainter>
#include <QMovie>
#include <QMouseEvent>

MainInterface::MainInterface(QWidget *parent)
    : QMainWindow(parent, Qt::FramelessWindowHint)
    , ui(new Ui::MainInterface)
{
    ui->setupUi(this);

    //this->setWindowFlags(this->windowFlags() &~ (Qt::WindowMinMaxButtonsHint));
    //棱角圆滑
    QBitmap bmp(this->size());
    bmp.fill();
    QPainter p(&bmp);
    p.setPen(Qt::NoPen);
    p.setBrush(Qt::black);
    p.setPen(Qt::transparent);//表示RGBA值为(0,0,0,0)的透明色。
    p.setRenderHint(QPainter::Antialiasing); // 反锯齿;
    p.drawRoundedRect(bmp.rect(), 20, 20);
    setMask(bmp);

    //关闭按钮
    ui->closePushButton->setStyleSheet("QPushButton{border-image: url(:/Image/closeButton.png)}");

    //关闭按钮
    connect(ui->closePushButton, &QPushButton::clicked,
            this, [&](){
                // if(m_routeExamLoginStatus == true || m_examineExamLoginStatus == true){
                //     auto button = QMessageBox::warning(this,  tr("信息提示"),
                //                                        QString("环车检查端或驾驶端正在有学员登录，请退出登陆后，再操作，谢谢！").arg(g_routeEquipmentUsername),  QString("确定"),  0);

                //     if (button == 0){//退出程序

                //     }
                // }else{
                    exit(0);
                // }
            });

    //初始化界面
    initializeMainInterfaceSetStyleSheet();

    initializeExamineExamManagePageSetStyleSheet();

    initializeRouteExamManagePageSetStyleSheet();

    initializeTampingHomeworkExamManagePageSetStyleSheet();


    //主界面切换
    ui->equipmentManagePageLabel_1->installEventFilter(this);
    ui->equipmentManagePageLabel_2->installEventFilter(this);
    ui->equipmentManagePageLabel_3->installEventFilter(this);

    ui->examineExamManagePageLabel_0->installEventFilter(this);
    ui->examineExamManagePageLabel_2->installEventFilter(this);
    ui->examineExamManagePageLabel_3->installEventFilter(this);

    ui->routeExamManagePageLabel_0->installEventFilter(this);
    ui->routeExamManagePageLabel_1->installEventFilter(this);
    ui->routeExamManagePageLabel_3->installEventFilter(this);

    ui->tampingHomeworkExamManagePageLabel_0->installEventFilter(this);
    ui->tampingHomeworkExamManagePageLabel_1->installEventFilter(this);
    ui->tampingHomeworkExamManagePageLabel_2->installEventFilter(this);

    //进入登录界面
    ui->tampingHomeworkTrainingLabel->installEventFilter(this);

    //旋转等待界面
    m_waitProcessBar  = new WaitProcessBar(this);

    //初始化监听线程
    initializeNetworkStatusThread();

    //初始化服务器
   initializeTcpServer();

    // //开启tcp服务
   startTcpServer();

}

MainInterface::~MainInterface()
{
    //退出网络监控的线程
    m_dealNetworkStatusThread.quit();//停止事件循环
    m_dealNetworkStatusThread.wait();//阻塞知道线程结束

    //关闭全部套接字
    emit closeAllSocket();

    //关闭数据库
    QSqlDatabase db = QSqlDatabase::database(m_databaseConnectedName);
    db.close();
    db = QSqlDatabase();
    QSqlDatabase::removeDatabase(m_databaseConnectedName);//断开与数据库的连接

    delete ui;
}

void MainInterface::initializeMainInterfaceSetStyleSheet()
{
    //背景动图
    QMovie *movie = new QMovie(":/Image/background.gif");
    ui->equipmentManageBackgroundLabel->setMovie(movie);
    movie->start();

    QPixmap icoPix;

    //equipmentManageBackgroundTitleLabel
    icoPix.load(":/Image/backupgroundTitle.png");
    icoPix.scaled(ui->equipmentManageBackgroundTitleLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->equipmentManageBackgroundTitleLabel->setScaledContents(true);
    ui->equipmentManageBackgroundTitleLabel->setPixmap(icoPix);

    icoPix.load(":/Image/examine.png");
    icoPix.scaled(ui->examineLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->examineLabel->setScaledContents(true);
    ui->examineLabel->setPixmap(icoPix);

    icoPix.load(":/Image/route.png");
    icoPix.scaled(ui->routeLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->routeLabel->setScaledContents(true);
    ui->routeLabel->setPixmap(icoPix);

    icoPix.load(":/Image/tampingHomework.png");
    icoPix.scaled(ui->tampingHomeworkLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->tampingHomeworkLabel->setScaledContents(true);
    ui->tampingHomeworkLabel->setPixmap(icoPix);

    icoPix.load(":/Image/tampingHomework.png");
    icoPix.scaled(ui->tampingHomeworkLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->tampingHomeworkLabel->setScaledContents(true);
    ui->tampingHomeworkLabel->setPixmap(icoPix);

    icoPix.load(":/Image/training.png");
    icoPix.scaled(ui->examineTrainingLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->examineTrainingLabel->setScaledContents(true);
    ui->examineTrainingLabel->setPixmap(icoPix);

    icoPix.load(":/Image/exam.png");
    icoPix.scaled(ui->examineExamLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->examineExamLabel->setScaledContents(true);
    ui->examineExamLabel->setPixmap(icoPix);

    icoPix.load(":/Image/training.png");
    icoPix.scaled(ui->routeTrainingLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->routeTrainingLabel->setScaledContents(true);
    ui->routeTrainingLabel->setPixmap(icoPix);

    icoPix.load(":/Image/exam.png");
    icoPix.scaled(ui->routeExamLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->routeExamLabel->setScaledContents(true);
    ui->routeExamLabel->setPixmap(icoPix);

    icoPix.load(":/Image/training.png");
    icoPix.scaled(ui->tampingHomeworkTrainingLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->tampingHomeworkTrainingLabel->setScaledContents(true);
    ui->tampingHomeworkTrainingLabel->setPixmap(icoPix);

    icoPix.load(":/Image/exam.png");
    icoPix.scaled(ui->tampingHomeworkExamLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->tampingHomeworkExamLabel->setScaledContents(true);
    ui->tampingHomeworkExamLabel->setPixmap(icoPix);

    icoPix.load(":/Image/equipmentStatusBackground.png");
    icoPix.scaled(ui->equipmentStatusBackgroundLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->equipmentStatusBackgroundLabel->setScaledContents(true);
    ui->equipmentStatusBackgroundLabel->setPixmap(icoPix);

    icoPix.load(":/Image/examineEquipmentOffline.png");
    icoPix.scaled(ui->examineEquipmentStatusLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->examineEquipmentStatusLabel->setScaledContents(true);
    ui->examineEquipmentStatusLabel->setPixmap(icoPix);


    icoPix.load(":/Image/routeEquipmentOffline.png");
    icoPix.scaled(ui->routeEquipmentStatusLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->routeEquipmentStatusLabel->setScaledContents(true);
    ui->routeEquipmentStatusLabel->setPixmap(icoPix);

    icoPix.load(":/Image/tampingHomeworkEquipmentOffline.png");
    icoPix.scaled(ui->tampingHomeworkEquipmentStatusLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->tampingHomeworkEquipmentStatusLabel->setScaledContents(true);
    ui->tampingHomeworkEquipmentStatusLabel->setPixmap(icoPix);

    icoPix.load(":/Image/lowerComputerEquipmentOffline.png");
    icoPix.scaled(ui->lowerComputerEquipmentStatusLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->lowerComputerEquipmentStatusLabel->setScaledContents(true);
    ui->lowerComputerEquipmentStatusLabel->setPixmap(icoPix);


    icoPix.load(":/Image/examineExamManagePage.png");
    icoPix.scaled(ui->examineExamManagePageLabel_0->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->examineExamManagePageLabel_0->setScaledContents(true);
    ui->examineExamManagePageLabel_0->setPixmap(icoPix);

    icoPix.load(":/Image/routeExamManagePage.png");
    icoPix.scaled(ui->routeExamManagePageLabel_0->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->routeExamManagePageLabel_0->setScaledContents(true);
    ui->routeExamManagePageLabel_0->setPixmap(icoPix);

    icoPix.load(":/Image/tampingHomeworkExamManagePage.png");
    icoPix.scaled(ui->tampingHomeworkExamManagePageLabel_0->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->tampingHomeworkExamManagePageLabel_0->setScaledContents(true);
    ui->tampingHomeworkExamManagePageLabel_0->setPixmap(icoPix);








}

void MainInterface::initializeExamineExamManagePageSetStyleSheet()
{
    QPixmap icoPix;

    icoPix.load(":/Image/routeExamManagePage.png");
    icoPix.scaled(ui->routeExamManagePageLabel_1->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->routeExamManagePageLabel_1->setScaledContents(true);
    ui->routeExamManagePageLabel_1->setPixmap(icoPix);

    icoPix.load(":/Image/tampingHomeworkExamManagePage.png");
    icoPix.scaled(ui->tampingHomeworkExamManagePageLabel_1->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->tampingHomeworkExamManagePageLabel_1->setScaledContents(true);
    ui->tampingHomeworkExamManagePageLabel_1->setPixmap(icoPix);

    icoPix.load(":/Image/equipmentManagePage.png");
    icoPix.scaled(ui->equipmentManagePageLabel_1->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->equipmentManagePageLabel_1->setScaledContents(true);
    ui->equipmentManagePageLabel_1->setPixmap(icoPix);

    icoPix.load(":/Image/backupgroundTitle.png");
    icoPix.scaled(ui->examineExamManageBackgroundTitleLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->examineExamManageBackgroundTitleLabel->setScaledContents(true);
    ui->examineExamManageBackgroundTitleLabel->setPixmap(icoPix);

    icoPix.load(":/Image/background.png");
    icoPix.scaled(ui->examineExamManageBackgroundLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->examineExamManageBackgroundLabel->setScaledContents(true);
    ui->examineExamManageBackgroundLabel->setPixmap(icoPix);


}

void MainInterface::initializeRouteExamManagePageSetStyleSheet()
{
    QPixmap icoPix;

    icoPix.load(":/Image/examineExamManagePage.png");
    icoPix.scaled(ui->examineExamManagePageLabel_2->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->examineExamManagePageLabel_2->setScaledContents(true);
    ui->examineExamManagePageLabel_2->setPixmap(icoPix);

    icoPix.load(":/Image/tampingHomeworkExamManagePage.png");
    icoPix.scaled(ui->tampingHomeworkExamManagePageLabel_2->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->tampingHomeworkExamManagePageLabel_2->setScaledContents(true);
    ui->tampingHomeworkExamManagePageLabel_2->setPixmap(icoPix);

    icoPix.load(":/Image/equipmentManagePage.png");
    icoPix.scaled(ui->equipmentManagePageLabel_2->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->equipmentManagePageLabel_2->setScaledContents(true);
    ui->equipmentManagePageLabel_2->setPixmap(icoPix);


    icoPix.load(":/Image/backupgroundTitle.png");
    icoPix.scaled(ui->routeExamManageBackgroundTitleLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->routeExamManageBackgroundTitleLabel->setScaledContents(true);
    ui->routeExamManageBackgroundTitleLabel->setPixmap(icoPix);

    icoPix.load(":/Image/background.png");
    icoPix.scaled(ui->routeExamManageBackgroundLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->routeExamManageBackgroundLabel->setScaledContents(true);
    ui->routeExamManageBackgroundLabel->setPixmap(icoPix);
}

void MainInterface::initializeTampingHomeworkExamManagePageSetStyleSheet()
{
    QPixmap icoPix;

    //equipmentManageBackgroundTitleLabel
    icoPix.load(":/Image/examineExamManagePage.png");
    icoPix.scaled(ui->examineExamManagePageLabel_3->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->examineExamManagePageLabel_3->setScaledContents(true);
    ui->examineExamManagePageLabel_3->setPixmap(icoPix);

    icoPix.load(":/Image/routeExamManagePage.png");
    icoPix.scaled(ui->routeExamManagePageLabel_3->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->routeExamManagePageLabel_3->setScaledContents(true);
    ui->routeExamManagePageLabel_3->setPixmap(icoPix);

    icoPix.load(":/Image/equipmentManagePage.png");
    icoPix.scaled(ui->equipmentManagePageLabel_3->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->equipmentManagePageLabel_3->setScaledContents(true);
    ui->equipmentManagePageLabel_3->setPixmap(icoPix);

    icoPix.load(":/Image/background.png");
    icoPix.scaled(ui->tampingHomworkExamManageBackgroundLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->tampingHomworkExamManageBackgroundLabel->setScaledContents(true);
    ui->tampingHomworkExamManageBackgroundLabel->setPixmap(icoPix);

    icoPix.load(":/Image/backupgroundTitle.png");
    icoPix.scaled(ui->tampingHomworkExamManageBackgroundTitleLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->tampingHomworkExamManageBackgroundTitleLabel->setScaledContents(true);
    ui->tampingHomworkExamManageBackgroundTitleLabel->setPixmap(icoPix);

}

//事件过滤器
bool MainInterface::eventFilter(QObject *obj, QEvent *event)
{
    if(obj == ui->equipmentManagePageLabel_1){//切换到设备管理界面
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                ui->stackedWidget->setCurrentIndex(0);
                return true;
            }else return false;
        }else return false;
    }
    else if(obj == ui->equipmentManagePageLabel_2){
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                ui->stackedWidget->setCurrentIndex(0);
                return true;
            }else return false;
        }else return false;
    }
    else if(obj == ui->equipmentManagePageLabel_3){
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                ui->stackedWidget->setCurrentIndex(0);
                return true;
            }else return false;
        }else return false;
    }
    else if(obj == ui->examineExamManagePageLabel_0){
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                ui->stackedWidget->setCurrentIndex(1);
                return true;
            }else return false;
        }else return false;
    }
    else if(obj == ui->examineExamManagePageLabel_2){
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                ui->stackedWidget->setCurrentIndex(1);
                return true;
            }else return false;
        }else return false;
    }
    else if(obj == ui->examineExamManagePageLabel_3){
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                ui->stackedWidget->setCurrentIndex(1);
                return true;
            }else return false;
        }else return false;
    }

    else if(obj == ui->routeExamManagePageLabel_0){
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                ui->stackedWidget->setCurrentIndex(2);
                return true;
            }else return false;
        }else return false;
    }
    else if(obj == ui->routeExamManagePageLabel_1){
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                ui->stackedWidget->setCurrentIndex(2);
                return true;
            }else return false;
        }else return false;
    }
    else if(obj == ui->routeExamManagePageLabel_3){
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                ui->stackedWidget->setCurrentIndex(2);
                return true;
            }else return false;
        }else return false;
    }

    else if(obj == ui->tampingHomeworkExamManagePageLabel_0){
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                ui->stackedWidget->setCurrentIndex(3);
                return true;
            }else return false;
        }else return false;
    }
    else if(obj == ui->tampingHomeworkExamManagePageLabel_1){
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                ui->stackedWidget->setCurrentIndex(3);
                return true;
            }else return false;
        }else return false;
    }
    else if(obj == ui->tampingHomeworkExamManagePageLabel_2){
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                ui->stackedWidget->setCurrentIndex(3);
                return true;
            }else return false;
        }else return false;
    }

    else if(obj == ui->tampingHomeworkTrainingLabel){
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                if(m_tampingHomeworkEquipmentStatus == false){
                    auto button = QMessageBox::information(this,  tr("信息提示"),
                                                           QString("请等待捣固端上线后，再操作，谢谢。"),  QString("确定"),  0);
                    if (button == 0) {//修改记录信息

                    }
                }
                else{
                    if(m_tampingHomeworkEquipmentLoginStatus == false){
                        emit show2LoginDialog(ClientHashEnum::TampingHomeworkEquipment, ExamType::TampingHomeworkExam, ExamPatternType::TrainingType);
                    }
                }

                return true;
            }else return false;
        }else return false;
    }


    else return MainInterface::eventFilter(obj, event);
}

void MainInterface::sendLoginInformation(QString username, int equipmentType, int examType, int examPatternType, QHash<QString, QList<int> > faultType)
{
    //临时存储设备登录信息
    m_saveUsername = username;
    m_saveEquipmentType = equipmentType;
    m_saveExamType = examType;
    m_saveExamPatternType = examPatternType;
    m_saveFaultType = faultType;

    // emit m_server->sendUserLogInformation(equipmentType, examType, examPatternType, username, faultType);

    m_waitProcessBar->startTimer();
}

void MainInterface::startTcpServer()
{
    m_listenIp = getLocalIP();
    qDebug()<<"目前获得的ip:"<<m_listenIp;
    if(m_listenIp == "127.0.0.1" ){//如果是本地ip，则一直重复要求联网
        while(true){
            if(m_serverStatus == true){
                break;
            }
            auto button = QMessageBox::question(this,  tr("信息提示"),
                                                QString("是否已连接网络？"),  QString("确定"),  0);
            if (button == 0) {
                startTcpServer();
            }
        }
    }else{
        while(m_listenPort < 20000){//遍历寻找可以监听的端口
            if(m_server->start(m_listenIp, m_listenPort)){
                qDebug()<<QString("开始监听%1 : %2").arg(m_listenIp).arg(m_listenPort);
                m_serverStatus = true;

                QSqlQuery query(QSqlDatabase::database(m_databaseConnectedName));
                //REPLACE INTO users (id,name,age) VALUES(123, '贾斯丁比伯', 22);
                QString sql = QString("REPLACE INTO equipment_server_information (serial_number, ip, port, online) "
                                      "VALUES(\'%1\', \'%2\', %3, %4)")
                                  .arg(QString("00000002"))
                                  .arg(m_listenIp)
                                  .arg(m_listenPort)
                                  .arg(1);

                if(!query.exec(sql)){
                    qDebug()<<query.lastError().databaseText();
                }

                break;
            }else{
                m_listenPort++;
            }
        }
    }
}

//初始化服务器套接字
void MainInterface::initializeTcpServer()
{
    //m_server = new TcpServer(this);
    m_server = new TcpServer();

    connect(m_server, &TcpServer::acceptError,
            this, [&](QAbstractSocket::SocketError socketError){
        //qDebug()<<m_server->errorString();
        qDebug()<<"socketError:"<<socketError;
    });

    //客户端连接
    connect(m_server, &TcpServer::clientConnected,
            this, &MainInterface::clientConnected);

    //客户端断开连接
    connect(m_server, &TcpServer::clientDisconnected,
            this, &MainInterface::clientDisconnected);

    //发送的数据
    connect(m_server, &TcpServer::sendSocketData,
            this, [](const QString &ip, int port, const QString &data){
        qDebug()<<QString("发送客户端 %1 : %2 ：%3").arg(ip).arg(port).arg(data);
    });

    //接收到的数据
    connect(m_server,  &TcpServer::receiveData,
            this, [](const QString &ip, int port, const QString &data){
        qDebug()<<QString("收到客户端 %1 : %2 ：%3").arg(ip).arg(port).arg(data);
    });

    //关闭套接字
    connect(this, &MainInterface::closeServer,
            m_server, &TcpServer::closeServer);

    connect(this, &MainInterface::closeOneSocket,
            m_server, &TcpServer::closeOneSocket);

    connect(this, &MainInterface::closeAllSocket,
            m_server, &TcpServer::closeAllSocket);

    //传递unity客户端的状态(在线、离线、已登录、未登录);株所设备的状态

    connect(m_server, &TcpServer::conveyEquipmentStatusType, this, [&](int status){
        qDebug()<<"&TcpServer::conveyEquipmentStatusType"<<QThread::currentThreadId() << QThread::currentThread();

         QPixmap icoPix;

        if(status == EquipmentStatusType::ExamineExamUnityEquipmentOnline){
             m_examineExamEquipmentStatus = true;

             icoPix.load(":/Image/examineEquipmentOnline.png");
             icoPix.scaled(ui->examineEquipmentStatusLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
             ui->examineEquipmentStatusLabel->setScaledContents(true);
             ui->examineEquipmentStatusLabel->setPixmap(icoPix);
        }else if(status == EquipmentStatusType::ExamineExamUnityEquipmentOffline){
            icoPix.load(":/Image/examineEquipmentOffline.png");
            icoPix.scaled(ui->examineEquipmentStatusLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
            ui->examineEquipmentStatusLabel->setScaledContents(true);
            ui->examineEquipmentStatusLabel->setPixmap(icoPix);
        }else if(status == EquipmentStatusType::ExamineExamUnityEquipmentLogIn){
            icoPix.load(":/Image/endEquipmentActivity.png");
            icoPix.scaled(ui->endExamineEquipmentLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
            ui->endExamineEquipmentLabel->setScaledContents(true);
            ui->endExamineEquipmentLabel->setPixmap(icoPix);

            icoPix.load(":/Image/informationBackground.png");
            icoPix.scaled(ui->examineEquipmentInformationLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
            ui->examineEquipmentInformationLabel->setScaledContents(true);
            ui->examineEquipmentInformationLabel->setPixmap(icoPix);
        }else if(status == EquipmentStatusType::ExamineExamUnityEquipmentLogOut){

            ui->endExamineEquipmentLabel->hide();
            ui->examineEquipmentInformationLabel->hide();
        }
        else if(status == EquipmentStatusType::RouteExamUnityEquipmentOnline){
            m_routeExamEquipmentStatus = true;

            icoPix.load(":/Image/routeEquipmentOnline.png");
            icoPix.scaled(ui->routeEquipmentStatusLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
            ui->routeEquipmentStatusLabel->setScaledContents(true);
            ui->routeEquipmentStatusLabel->setPixmap(icoPix);
        }else if(status == EquipmentStatusType::RouteExamUnityEquipmentOffline){
            icoPix.load(":/Image/routeEquipmentOffline.png");
            icoPix.scaled(ui->routeEquipmentStatusLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
            ui->routeEquipmentStatusLabel->setScaledContents(true);
            ui->routeEquipmentStatusLabel->setPixmap(icoPix);
        }else if(status == EquipmentStatusType::RouteExamUnityEquipmentLogIn){
            icoPix.load(":/Image/endEquipmentActivity.png");
            icoPix.scaled(ui->endRouteEquipmentLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
            ui->endRouteEquipmentLabel->setScaledContents(true);
            ui->endRouteEquipmentLabel->setPixmap(icoPix);

            icoPix.load(":/Image/informationBackground.png");
            icoPix.scaled(ui->routeEquipmentInformationLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
            ui->routeEquipmentInformationLabel->setScaledContents(true);
            ui->routeEquipmentInformationLabel->setPixmap(icoPix);
        }else if(status == EquipmentStatusType::RouteExamUnityEquipmentLogOut){
            ui->endRouteEquipmentLabel->hide();
            ui->routeEquipmentInformationLabel->hide();
        }

        else if(status == EquipmentStatusType::TampingHomeworkEquipmentOnline){
            m_tampingHomeworkEquipmentStatus = true;

            icoPix.load(":/Image/tampingHomeworkEquipmentOnline.png");
            icoPix.scaled(ui->tampingHomeworkEquipmentStatusLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
            ui->tampingHomeworkEquipmentStatusLabel->setScaledContents(true);
            ui->tampingHomeworkEquipmentStatusLabel->setPixmap(icoPix);
        }else if(status == EquipmentStatusType::TampingHomeworkEquipmentOffline){
            icoPix.load(":/Image/tampingHomeworkEquipmentOffline.png");
            icoPix.scaled(ui->tampingHomeworkEquipmentStatusLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
            ui->tampingHomeworkEquipmentStatusLabel->setScaledContents(true);
            ui->tampingHomeworkEquipmentStatusLabel->setPixmap(icoPix);
        }else if(status == EquipmentStatusType::TampingHomeworkEquipmentLogIn){
            icoPix.load(":/Image/endEquipmentActivity.png");
            icoPix.scaled(ui->endTampingHomeworkEquipmentLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
            ui->endTampingHomeworkEquipmentLabel->setScaledContents(true);
            ui->endTampingHomeworkEquipmentLabel->setPixmap(icoPix);

            icoPix.load(":/Image/informationBackground.png");
            icoPix.scaled(ui->tampingHomeworkEquipmentInformationLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
            ui->tampingHomeworkEquipmentInformationLabel->setScaledContents(true);
            ui->tampingHomeworkEquipmentInformationLabel->setPixmap(icoPix);
        }else if(status == EquipmentStatusType::TampingHomeworkEquipmentLogOut){
            ui->endTampingHomeworkEquipmentLabel->hide();
            ui->tampingHomeworkEquipmentInformationLabel->hide();


        }

        else if(status == EquipmentStatusType::LowerComputerEquipmentOnline){

            icoPix.load(":/Image/lowerComputerEquipmentOnline.png");
            icoPix.scaled(ui->lowerComputerEquipmentStatusLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
            ui->lowerComputerEquipmentStatusLabel->setScaledContents(true);
            ui->lowerComputerEquipmentStatusLabel->setPixmap(icoPix);

        }else if(status == EquipmentStatusType::LowerComputerEquipmentOffline){
            icoPix.load(":/Image/lowerComputerEquipmentOffline.png");
            icoPix.scaled(ui->lowerComputerEquipmentStatusLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
            ui->lowerComputerEquipmentStatusLabel->setScaledContents(true);
            ui->lowerComputerEquipmentStatusLabel->setPixmap(icoPix);

        }

    });

}

void MainInterface::clientConnected(const QString &ip, int port)
{
    qDebug()<<QString("客户端上线: %1 : %2").arg(ip).arg(QString::number(port));
    clientConnectedList.append(QPair(ip, port));

}

void MainInterface::clientDisconnected(const QString &ip, int port)
{
    qDebug()<<QString("客户端下线: %1 : %2").arg(ip).arg(QString::number(port));
    clientConnectedList.removeOne(QPair(ip, port));
}

//初始化网络监听线程
void MainInterface::initializeNetworkStatusThread()
{
    m_dealNetworkStatus = new DealNetworkStatus;
    m_dealNetworkStatus->moveToThread(&m_dealNetworkStatusThread);
    //设置网络状态
    connect(m_dealNetworkStatus, &DealNetworkStatus::sendNetworkStatus,
            this, [&](int status){
                if(status == NetworkStatus::Normal){//外网正常
                    //qDebug()<<"NetworkStatus::Normal";
                }else if(status == NetworkStatus::Disconnect){//断网
                    emit stopMonitorNetworkStatus();
                    // qDebug()<<"NetworkStatus::Disconnect";

                    auto button = QMessageBox::warning(this,  tr("错误提示"),
                                                       QString("是否已重新连接网络？"),  QString("确定"),  0);
                    if (button == 0) {

                        emit startMonitorNetworkStatus();

                    }
                }
            });


    //是否启动网络状态监听
    connect(this, &MainInterface::startMonitorNetworkStatus,
            m_dealNetworkStatus, &DealNetworkStatus::startMonitorNetwork);

    connect(this, &MainInterface::stopMonitorNetworkStatus,
            m_dealNetworkStatus, &DealNetworkStatus::stopMonitorNetwork);

    connect(&m_dealNetworkStatusThread, &QThread::finished,
            this, &DealNetworkStatus::deleteLater);

    //设置线程优先级
    /*
    QThread::InheritPriority (给创建的线程赋予目前线程同样的等级（默认情况下就为这个）) ,
    QThread::TimeCriticalPriority (尽可能频繁的调度),
     QThread::HighestPriority  >  QThread::HighPriority >  QThread::NormalPriority(操作系统默认的优先级)
    > QThread::LowPriority > QThread::LowestPriority  >QThread::IdlePriority (没有其他线程运行的时候才进行调度)
      */
    // m_dealNetworkStatusThread.setPriority(QThread::InheritPriority);
    m_dealNetworkStatusThread.start();

    emit startMonitorNetworkStatus();
}
//获得全部ip
QStringList MainInterface::getLocalIPs()
{
    QStringList ips;
#ifdef emsdk
    ips << "127.0.0.1";
#else
    QList<QNetworkInterface> netInterfaces = QNetworkInterface::allInterfaces();
    foreach (const QNetworkInterface  &netInterface, netInterfaces) {
        //移除虚拟机和抓包工具的虚拟网卡
        QString humanReadableName = netInterface.humanReadableName().toLower();
        if (humanReadableName.startsWith("vmware network adapter") || humanReadableName.startsWith("npcap loopback adapter")) {
            continue;
        }

        //过滤当前网络接口
        bool flag = (netInterface.flags() == (QNetworkInterface::IsUp | QNetworkInterface::IsRunning | QNetworkInterface::CanBroadcast | QNetworkInterface::CanMulticast));
        if (flag) {
            QList<QNetworkAddressEntry> addrs = netInterface.addressEntries();
            foreach (QNetworkAddressEntry addr, addrs) {
                //只取出IPV4的地址
                if (addr.ip().protocol() == QAbstractSocket::IPv4Protocol) {
                    QString ip4 = addr.ip().toString();
                    if (ip4 != "127.0.0.1") {
                        ips.append(ip4);
                    }
                }
            }
        }
    }
#endif
    return ips;
}
//获得单独的ip
QString MainInterface::getLocalIP()
{
    //优先取192开头的IP,如果获取不到IP则取127.0.0.1
    QString ip = "127.0.0.1";
    QStringList ips = getLocalIPs();
    foreach (QString str, ips) {
        if (str.startsWith("192.168.1") || str.startsWith("192")) {
            ip = str;
            break;
        }
    }
    return ip;
}

